<?php

require_once dirname(__FILE__).'/object.php';
require_once dirname(__FILE__).'/extension.php';

class _F_REQUEST_ extends _F_OBJECT_ {

	public $theme;
	public $secure_connection;
	public $server;
	public $base_path;
	public $url_base;
	public $redirect;
	public $request;
	public $action;
	public $command;
	public $param;
	public $config;
	public $page_template = 'page';
	public $asset_manager;
	public $template_path_list = array();
	public $routes = array();	
	public $content = '';
	public $styles = array();
	public $scripts = array();
	public $page_title = 'Untitled Page';
	
	public static $_f_request_;
	
	public function __construct() {
		_F_REQUEST_::$_f_request_ = $this;
		$def_port = 80;
		$this->secure_connection = false;
		if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
			$this->secure_connection = true;
			$def_port = 443;
		}
		$this->server = ($this->secure_connection ? 'https://' : 
			'http://').$_SERVER['SERVER_NAME'];
		if ($_SERVER['SERVER_PORT'] != $def_port) 
			$this->server .= ':'.$_SERVER['SERVER_PORT'];
		$this->base_path = dirname($_SERVER['SCRIPT_FILENAME']);
		$this->template_path_list[] = $this->base_path.'/templates';
		$this->asset_management = 'checksum'; // full | checksum | disabled
		$this->asset_path = '/assets';
		$this->url_base = dirname(substr($_SERVER['SCRIPT_FILENAME'],
			strlen($_SERVER['DOCUMENT_ROOT'])));
		$this->register_method('route',array($this,'_f_route_'));
		if (isset($_SERVER['REDIRECT_URL'])) {
			$this->redirect = true;
			$this->request = substr($_SERVER['REDIRECT_URL'],
				strlen($this->url_base));
		} else {
			$this->redirect = false;
			$this->request = isset($_GET['_f_request_']) ? 
				$_GET['_f_request_'] : 'index'; 
		}
		// load config file
		$this->config = array();
		$config_file = $this->base_path.'/config.php';
		// TODO: a file_exiteket lehet cachelni majd
		if (file_exists($config_file)) require $config_file;
		if (isset($this->theme)) array_unshift($this->template_path_list,
			$this->base_path.'/themes/'.$this->theme.'/templates');
		// process page
		$this->route();
		ob_start();
		// TODO: ezt majd meglatjuk a gyakorlatban, mennyire okoz kavarodast
		// es a dokumentacionak is eleg vilagosnak kell lennie, hogy mikor
		// melyk actiont hasznalja
		if (isset($this->command)) {
			$action_file = $this->base_path.
				$this->action.'_'.$this->command.'.php';
			if (file_exists($action_file)) {
				$this->render_file($action_file,array('param' => $this->param));
			} else {
				$action_file = $this->base_path.$this->action.'.php';
				if (file_exists($action_file)) {
					$this->param = $this->command.
						(isset($this->param) ? ('/'.$this->param) : '');
					$this->render_file($action_file,array('param' => $this->param));
				} else {
					error_log("VerSimF Notice: Page '$action_file' does not exist.");
				}
			}
		} else {
			$action_file = $this->base_path.$this->action.'.php';
			if (file_exists($action_file)) {
				$this->render_file($action_file);
			} else {
				error_log("VerSimF Notice: Page '$action_file' does not exist.");
			}
		}
		$this->content = ob_get_clean();
		// process page template
		ob_start();
		if (isset($this->page_template)) $this->render($this->page_template); 
		$content = ob_get_clean();
		if (!empty($content)) $this->content = $content;
		if ($this->has_method('post_process_callback')) 
			$this->post_process_callback();
		echo $this->content;
	}
	
	public function _f_route_($request = null,$prefix = '/actions') {
		if ($request === null) $request = $this->request;
		$elements = preg_split('/\//',$request,3);
		while (count($elements) > 0 && $elements[0] == '') 
			array_shift($elements);
		$count = count($elements);
		if ($count > 0) {
			$this->action = $prefix.'/'.$elements[0];
			if ($count > 1) {
				$this->command = $elements[1];
				if ($count > 2) $this->param =  $elements[2];
			} 
		} else {
			$this->action = $prefix.'/'.'index';
		}
	}
	
	public function import($_f_name_,$_f_params_ = null) {
		if (is_array($_f_params_)) extract($_f_params_,EXTR_SKIP);
		require_once $this->base_path.'/extensions/'.
			$_f_name_.'/'.$_f_name_.'.php';
		return $this;
	}

	public function render($name,$params = null) {
		foreach ($this->template_path_list as $path) {
			$file = $path.'/'.$name.'.php';
			if (file_exists($file)) {
				$this->render_file($file,$params);
				return $this;
			}
		}
		error_log("Template $name is not found.");
		return $this;
	}
	
	public function render_content() {
		echo $this->content;
		return $this;
	}

	public function render_file($_f_file_,$_f_params_ = null) {
		if (is_array($_f_params_)) extract($_f_params_,EXTR_SKIP);
		require $_f_file_;
		return $this;
	}
	
	public function asset($name) {
		$file = $this->base_path.$name;
		if (file_exists($file) && $this->has_method('asset_manager_callback'))
			return $this->asset_manager_callback($name,$file);
		return $name;
	}

	// TODO: itt is vilagos es egyseges szabalyok kellenek
	// 
	// 0. ha a cim ures vagy csak whitespaceket tartalamaz, vagy egy darab '/' akkor 
	// 	  a site URLt adja vissza
	//
	// 1. ami '/' jellel kezdodik az relativ a {base_path}-hoz kepest 
	//	  es assetkent lesz feldolgozva
	// 
	// 2. ami '@' jellel kezdodik az a belso cimkent lesz feldolgozva
	//
	// 3. minden mas erintetlenul kerul be a cuccosba

	public function url($address,$get_parameters = false, $absolute = false) {
		if (is_array($get_parameters)) {
			$get_parameters = http_build_query($get_parameters);
		} else {
			$absolute = $get_parameters === true;
			$get_parameters = '';
		}
		if (!isset($address) || $address == '/' || trim($address) == '') {
			$url = $this->url_base;
		} else if ($address == '@') {
			return $this->url_base;
		} else if ($address{0} == '@') {
			$address = substr($address,1);
			if ($this->redirect) {
				$url = $this->url_base.'/'.$address.
					($get_parameters == '' ? '' : '?').
					$get_parameters;
			} else {
				$url = $this->url_base.'/index.php?'.$get_parameters.
					($get_parameters == '' ? '&' : '').
					'_f_request_='.urlencode($address);
			}
		} else if ($address{0} == '/') {
			$url =  $this->url_base.$this->asset($address);
		} else if ($get_parameters == '') { 
			$url = $address;
		} else {
			$url = $address.(strpos($address,'?') === false ?
			 	'?' : '&').$get_parameters;
		}		
		return $url;
	}
	
	public function param($name) {
		if (isset($_GET[$name])) return $_GET[$name];
		if (isset($_POST[$name])) return $_POST[$name];
		return null;
	}
	
	public function redirect($url,$permamnent = false) {
		if ($permamnent) header("HTTP/1.1 301 Moved Permanently");
		$location = 'Location: '.$this->url($url,true);
		header($location);	
	}

}

function f() {
	return _F_REQUEST_::$_f_request_;
}

function t($text,$context = null) {
	if (function_exists('_f_i18n_text_')) {
		return _f_i18n_text_($text,$context);
	}
	return $text;
}


new _F_REQUEST_;
